package org.jetlinks.pro.auth.dimension;

import lombok.AllArgsConstructor;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.authorization.Dimension;
import org.hswebframework.web.authorization.DimensionProvider;
import org.hswebframework.web.authorization.DimensionType;
import org.hswebframework.web.system.authorization.api.entity.DimensionUserEntity;
import org.hswebframework.web.system.authorization.defaults.service.DefaultDimensionUserService;
import org.hswebframework.web.system.authorization.defaults.service.terms.DimensionTerm;
import org.jetlinks.pro.auth.entity.OrganizationEntity;
import org.jetlinks.pro.authorize.OrgDimensionType;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Component
public class OrganizationDimensionProvider implements DimensionProvider {

    private final ReactiveRepository<OrganizationEntity, String> repository;

    private final DefaultDimensionUserService dimensionUserService;

    @Override
    public Flux<? extends DimensionType> getAllType() {
        return Flux.just(OrgDimensionType.org);
    }

    @Override
    public Flux<? extends Dimension> getDimensionByUserId(String s) {
        return DimensionTerm
            .inject(repository.createQuery(), "id", OrgDimensionType.org.getId(), Collections.singletonList(s))
            .fetch()
            .map(OrganizationEntity::toDimension)
            ;
    }

    @Override
    public Mono<? extends Dimension> getDimensionById(DimensionType dimensionType, String s) {
        if(!dimensionType.isSameType(OrgDimensionType.org)){
            return Mono.empty();
        }
        return repository
            .findById(s)
            .map(OrganizationEntity::toDimension);
    }

    @Override
    public Flux<? extends Dimension> getDimensionsById(DimensionType type, Collection<String> idList) {
        if(!type.isSameType(OrgDimensionType.org)){
            return Flux.empty();
        }
        return repository
            .findById(idList)
            .map(OrganizationEntity::toDimension);
    }

    @Override
    public Flux<String> getUserIdByDimensionId(String s) {
        return dimensionUserService
            .createQuery()
            .where(DimensionUserEntity::getDimensionId, s)
            .and(DimensionUserEntity::getDimensionTypeId, OrgDimensionType.org.getId())
            .fetch()
            .map(DimensionUserEntity::getUserId);
    }
}
